<template>
  <div class="create-business-scenario">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-left">
        <el-button 
          type="text" 
          @click="goBack"
          class="back-button"
        >
          <el-icon><ArrowLeft /></el-icon>
          返回
        </el-button>
        <h1 class="page-title">新建业务场景库</h1>
      </div>
    </div>

    <!-- 表单内容 -->
    <div class="form-container">
      <el-form 
        ref="formRef" 
        :model="form" 
        :rules="rules" 
        label-width="120px"
        class="knowledge-form"
      >
        <!-- 基本信息模块 -->
        <div class="form-section">
          <h2 class="section-title">基本信息</h2>
          <div class="section-content">
            <el-form-item label="知识库名称" prop="name" required>
              <el-input 
                v-model="form.name" 
                placeholder="请输入知识库名称"
                maxlength="50"
                show-word-limit
              />
            </el-form-item>
            
            <el-form-item label="知识库描述" prop="description" required>
              <el-input 
                v-model="form.description" 
                type="textarea" 
                placeholder="请输入知识库描述"
                :rows="4"
                maxlength="200"
                show-word-limit
              />
            </el-form-item>
          </div>
        </div>

        <!-- 数据源配置模块 -->
        <div class="form-section">
          <h2 class="section-title">数据源配置</h2>
          <div class="section-content">
            <!-- 业务数据表结构地址 -->
            <el-form-item label="数据表结构地址" prop="tableStructureUrl">
              <div class="table-structure-container">
                <el-input 
                  v-model="form.tableStructureUrl" 
                  placeholder="请输入业务数据表结构地址"
                  class="table-structure-input"
                />
                <el-button 
                  type="primary" 
                  @click="createBusinessTable"
                  class="create-table-btn"
                >
                  创建业务数据表
                </el-button>
              </div>
            </el-form-item>

            <!-- 本地文件上传 -->
            <el-form-item label="上传本地文件">
              <el-upload
                class="upload-demo"
                drag
                :http-request="handleUpload"
                multiple
                :accept="acceptedFileTypes"
                :on-success="handleUploadSuccess"
                :on-error="handleUploadError"
                :file-list="fileList"
              >
                <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持格式：{{ supportedFormats.join(', ') }}
                  </div>
                </template>
              </el-upload>
            </el-form-item>

            <!-- URL数据源 -->
            <el-form-item label="URL数据源">
              <!-- URL输入框列表 -->
              <div class="url-inputs-container">
                <div 
                  v-for="(urlItem, index) in form.urls" 
                  :key="index" 
                  class="url-input-row"
                >
                  <el-input 
                    v-model="urlItem.url" 
                    placeholder="请输入URL地址"
                    class="url-input"
                  />
                  <el-select 
                    v-model="urlItem.type" 
                    placeholder="选择URL类型"
                    class="url-type-select"
                    :class="{ 'is-error': urlItem.url && !urlItem.type }"
                  >
                    <el-option label="小红书" value="小红书" />
                    <el-option label="微信公众号" value="微信公众号" />
                  </el-select>
                  <el-button 
                    type="danger" 
                    plain
                    size="small"
                    @click="removeUrl(index)"
                    class="delete-btn"
                  >
                    删除
                  </el-button>
                </div>
                
                <!-- 添加URL按钮行 -->
                <div class="add-url-row">
                  <el-button 
                    type="success" 
                    plain
                    @click="addUrl"
                    class="add-url-btn"
                  >
                    + 添加URL
                  </el-button>
                </div>
              </div>
            </el-form-item>
          </div>
        </div>

        <!-- 操作按钮 -->
        <div class="form-actions">
          <el-button @click="goBack">取消</el-button>
          <el-button type="primary" @click="submitForm">创建知识库</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElLoading } from 'element-plus'
import axios from 'axios'

export default {
  name: 'CreateBusinessScenario',
  setup() {
    const router = useRouter()
    const formRef = ref()
    
    // 支持的文件格式
    const supportedFormats = ['TXT', 'MD', 'MARKDOWN', 'PDF', 'HTML', 'XLSX', 'XLS', 'DOCX', 'CSV', 'EML', 'MSG', 'PPTX', 'PPT', 'XML', 'EPUB']
    const acceptedFileTypes = supportedFormats.map(format => `.${format.toLowerCase()}`).join(',')
    
    // 表单数据
    const form = reactive({
      name: '',
      description: '',
      tableStructureUrl: '',
      urls: [],
      dataSourceType: ''
    })

    // 文件列表和上传的文件ID
    const fileList = ref([])
    const uploadedFiles = ref([])

    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入知识库名称', trigger: 'blur' },
        { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
      ],
      description: [
        { required: true, message: '请输入知识库描述', trigger: 'blur' },
        { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
      ]
    }

    // 上传配置 - 使用自定义上传
    const uploadAction = ''

    // API配置
    const API_CONFIG = {
      uploadUrl: '/api/v1/files/upload',  // 使用代理路径
      workflowUrl: '/api/v1/workflows/run',  // 使用代理路径
      authorization: 'Bearer app-OFk8vj2CnslsVRKjr2mAtJEr',
      apiKey: 'app-OFk8vj2CnslsVRKjr2mAtJEr'
    }

    // 返回上一页
    const goBack = () => {
      router.back()
    }

    // 添加URL
    const addUrl = () => {
      console.log('尝试添加URL:', {
        timestamp: new Date().toISOString()
      })

      const urlItem = {
        url: '',
        type: ''
      }

      form.urls.push(urlItem)
      console.log('URL添加成功:', urlItem, '当前URL数量:', form.urls.length)
    }

    // 创建业务数据表
    const createBusinessTable = () => {
      // 这里处理创建业务数据表的逻辑
      ElMessage.info('创建业务数据表功能待实现')
    }

    // 移除URL
    const removeUrl = (index) => {
      console.log('删除URL:', {
        index,
        url: form.urls[index]?.url,
        timestamp: new Date().toISOString()
      })
      
      if (index >= 0 && index < form.urls.length) {
        const removedUrl = form.urls.splice(index, 1)[0]
        console.log('URL已从列表中移除:', removedUrl, '当前URL数量:', form.urls.length)
        ElMessage.success('URL已删除')
      } else {
        console.warn('无效的URL索引:', index)
      }
    }

    // 获取URL类型标签文本
    const getUrlTypeLabel = (type) => {
      const typeMap = {
        xiaohongshu: '小红书',
        wechat: '微信公众号'
      }
      return typeMap[type] || type
    }

    // 自定义文件上传
    const handleUpload = async (options) => {
      const { file } = options
      console.log('开始上传文件:', {
        fileName: file.name,
        fileSize: file.size,
        fileType: file.type,
        timestamp: new Date().toISOString()
      })
      
      const formData = new FormData()
      
      // 根据文件类型设置MIME类型
      const fileExtension = file.name.split('.').pop().toLowerCase()
      let mimeType = file.type
      
      console.log('文件扩展名:', fileExtension, '原始MIME类型:', mimeType)
      
      // 如果是图片文件，设置正确的MIME类型
      if (['png', 'jpeg', 'jpg', 'webp', 'gif'].includes(fileExtension)) {
        mimeType = `image/${fileExtension === 'jpg' ? 'jpeg' : fileExtension}`
        console.log('更新后的MIME类型:', mimeType)
      }
      
      formData.append('file', file, file.name)
      formData.append('user', 'abc-123')

      console.log('准备发送请求到:', API_CONFIG.uploadUrl)
      console.log('完整请求URL:', `${window.location.origin}${API_CONFIG.uploadUrl}`)
      console.log('请求头Authorization:', API_CONFIG.authorization)

      try {
        const response = await axios.post(API_CONFIG.uploadUrl, formData, {
          headers: {
            'Authorization': API_CONFIG.authorization,
            // 不要手动设置Content-Type，让浏览器自动设置multipart边界
          },
          timeout: 60000, // 增加到60秒超时
          withCredentials: false,
          // 添加请求拦截器来调试
          validateStatus: function (status) {
            return status < 500; // 只有5xx错误才被认为是错误
          },
          onUploadProgress: (progressEvent) => {
            const percentCompleted = Math.round((progressEvent.loaded * 100) / progressEvent.total)
            console.log(`文件上传进度: ${percentCompleted}%`)
          }
        })

        console.log('文件上传响应:', {
          status: response.status,
          statusText: response.statusText,
          headers: response.headers,
          data: response.data
        })

        // 检查响应状态
        if (response.status === 405) {
          throw new Error('服务器不支持POST方法，请检查API端点是否正确')
        }

        if (response.status >= 400) {
          throw new Error(`服务器错误: ${response.status} ${response.statusText}`)
        }

        if (response.data && response.data.id) {
          // 保存上传成功的文件信息
          const fileInfo = {
            id: response.data.id,
            name: response.data.name,
            size: response.data.size,
            extension: response.data.extension,
            mime_type: response.data.mime_type,
            type: getSupportedFileType(response.data.extension),
            uploadTime: new Date().toISOString()
          }
          
          uploadedFiles.value.push(fileInfo)
          console.log('文件信息已保存:', fileInfo)
          
          ElMessage.success(`${file.name} 上传成功`)
          return response.data
        } else {
          console.error('响应数据格式异常，缺少id字段:', response.data)
          throw new Error('服务器响应格式异常')
        }
      } catch (error) {
        console.error('文件上传失败，详细错误信息:')
        console.error('错误类型:', error.name)
        console.error('错误消息:', error.message)
        console.error('错误堆栈:', error.stack)
        
        if (error.response) {
          // 服务器响应了错误状态码
          console.error('响应状态码:', error.response.status)
          console.error('响应状态文本:', error.response.statusText)
          console.error('响应数据:', error.response.data)
          console.error('响应头:', error.response.headers)
          
          let errorMessage = `上传失败: ${error.response.status} ${error.response.statusText}`
          if (error.response.status === 405) {
            errorMessage = '上传失败: 服务器不支持此请求方法，请联系管理员检查API配置'
          } else if (error.response.data && error.response.data.message) {
            errorMessage += ` - ${error.response.data.message}`
          }
          ElMessage.error(errorMessage)
        } else if (error.request) {
          // 请求已发出但没有收到响应
          console.error('请求已发出但没有收到响应:', error.request)
          ElMessage.error(`${file.name} 上传失败: 网络连接问题，请检查网络或联系管理员`)
        } else {
          // 其他错误
          console.error('请求配置错误:', error.message)
          ElMessage.error(`${file.name} 上传失败: ${error.message}`)
        }
        
        throw error
      }
    }

    // 获取支持的文件类型
    const getSupportedFileType = (extension) => {
      const imageTypes = ['png', 'jpeg', 'jpg', 'webp', 'gif']
      if (imageTypes.includes(extension.toLowerCase())) {
        return 'image'
      }
      return 'document'
    }

    // 文件上传成功
    const handleUploadSuccess = (response, file, fileList) => {
      // 由于使用自定义上传，这个方法可能不会被调用
    }

    // 文件上传失败
    const handleUploadError = (error, file, fileList) => {
      ElMessage.error(`${file.name} 上传失败`)
    }

    // 调用工作流接口
    const executeWorkflow = async (urlItem, fileInputs) => {
      console.log('开始执行工作流:', {
        url: urlItem.url,
        type: urlItem.type,
        fileInputsCount: fileInputs.length,
        apiUrl: form.tableStructureUrl,
        timestamp: new Date().toISOString()
      })

      try {
        const requestData = {
          inputs: {
            file: fileInputs,
            pc_type: urlItem.type,  // 将 pc_type 移到 inputs 对象内部
            url: urlItem.url,       // 也将 url 移到 inputs 内部
            api_url: form.tableStructureUrl  // 也将 api_url 移到 inputs 内部
          },
          response_mode: "streaming",
          user: "abc-123"
        }

        console.log('工作流请求数据:', JSON.stringify(requestData, null, 2))
        console.log('请求URL:', API_CONFIG.workflowUrl)
        console.log('请求头Authorization:', `Bearer ${API_CONFIG.apiKey}`)

        const response = await axios.post(API_CONFIG.workflowUrl, requestData, {
          headers: {
            'Authorization': `Bearer ${API_CONFIG.apiKey}`,
            'Content-Type': 'application/json'
          },
          timeout: 60000 // 60秒超时
        })

        console.log('工作流执行成功，响应数据:', response.data)
        console.log('响应状态:', response.status)
        console.log('响应头:', response.headers)

        return response.data
      } catch (error) {
        console.error('工作流执行失败，详细错误信息:')
        console.error('错误类型:', error.name)
        console.error('错误消息:', error.message)
        console.error('错误堆栈:', error.stack)
        
        if (error.response) {
          console.error('响应状态码:', error.response.status)
          console.error('响应状态文本:', error.response.statusText)
          console.error('响应数据:', error.response.data)
          console.error('响应头:', error.response.headers)
          
          // 处理特定的错误情况
          if (error.response.status === 400 && error.response.data) {
            const errorData = error.response.data
            if (errorData.message === 'Workflow not published') {
              ElMessage.error('工作流未发布，请联系管理员配置工作流')
            } else {
              ElMessage.error(`工作流执行失败: ${errorData.message || '未知错误'}`)
            }
          } else {
            ElMessage.error(`工作流执行失败: ${error.response.status} ${error.response.statusText}`)
          }
        } else if (error.request) {
          console.error('请求已发出但没有收到响应:', error.request)
          ElMessage.error('工作流执行失败: 网络连接问题')
        } else {
          console.error('请求配置错误:', error.message)
          ElMessage.error(`工作流执行失败: ${error.message}`)
        }
        
        // 所有错误都抛出，不再有特殊处理
        throw error
      }
    }

    // 提交表单
    const submitForm = async () => {
      console.log('开始创建知识库:', {
        name: form.name,
        description: form.description,
        tableStructureUrl: form.tableStructureUrl,
        urlsCount: form.urls.length,
        uploadedFilesCount: uploadedFiles.value.length,
        timestamp: new Date().toISOString()
      })

      // 表单验证
      if (!formRef.value) return
      
      try {
        await formRef.value.validate()
      } catch (error) {
        console.error('表单验证失败:', error)
        ElMessage.error('请完善必填信息')
        return
      }

      // 验证是否有数据源
      const hasFiles = uploadedFiles.value.length > 0
      const hasUrls = form.urls.length > 0
      
      if (!hasFiles && !hasUrls) {
        ElMessage.error('请至少上传一个文件或添加一个URL')
        return
      }

      // 验证URL数据源
      if (hasUrls) {
        // 检查是否有空的URL
        const emptyUrls = form.urls.filter(urlItem => !urlItem.url.trim())
        if (emptyUrls.length > 0) {
          ElMessage.error('请填写所有URL地址或删除空的URL项')
          return
        }

        // 检查是否有未选择类型的URL
        const urlsWithoutType = form.urls.filter(urlItem => urlItem.url.trim() && !urlItem.type)
        if (urlsWithoutType.length > 0) {
          ElMessage.error(`请为所有URL选择类型（小红书或微信公众号），有 ${urlsWithoutType.length} 个URL未选择类型`)
          return
        }

        // 验证URL格式
        const invalidUrls = form.urls.filter(urlItem => {
          if (!urlItem.url.trim()) return false
          try {
            new URL(urlItem.url)
            return false
          } catch {
            return true
          }
        })
        
        if (invalidUrls.length > 0) {
          ElMessage.error('请检查URL格式是否正确')
          return
        }
      }

      // 创建场景数据，用于传递给详情页面
      const scenarioData = {
        id: Date.now(), // 临时ID
        name: form.name,
        description: form.description,
        status: 'processing',
        workflows: [],
        hasFiles: hasFiles,
        hasUrls: hasUrls,
        urlsCount: form.urls.length,
        filesCount: uploadedFiles.value.length
      }

      // 立即跳转到业务场景详情页面，传递场景数据
      ElMessage.success('知识库创建中，正在跳转...')
      
      // 显示加载提示
      const loadingInstance = ElLoading.service({
        lock: true,
        text: '正在创建知识库，请稍候...',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      
      router.push({
        path: '/knowledge/business-scenario-detail',
        query: {
          newScenario: JSON.stringify(scenarioData)
        }
      }).then(() => {
        // 页面跳转完成后关闭加载提示
        setTimeout(() => {
          loadingInstance.close()
        }, 500)
      }).catch((error) => {
        console.error('页面跳转失败:', error)
        loadingInstance.close()
        ElMessage.error('页面跳转失败，请重试')
      })

      // 异步执行工作流处理
      setTimeout(() => {
        processWorkflowsAsync(scenarioData)
      }, 1000) // 延迟1秒执行，确保页面跳转完成
    }

    // 异步处理工作流
    const processWorkflowsAsync = async (scenarioData) => {
      try {
        // 准备文件输入数据
        const fileInputs = uploadedFiles.value.map(file => ({
          transfer_method: "local_file",
          upload_file_id: file.id,
          type: file.type
        }))

        console.log('异步处理工作流开始:', scenarioData.id)

        let successCount = 0
        let failureCount = 0
        const results = []

        // 如果有URL数据源，循环调用工作流接口
        if (form.urls && form.urls.length > 0) {
          const validUrls = form.urls.filter(urlItem => urlItem.url && urlItem.type)
          console.log(`开始处理 ${validUrls.length} 个有效URL`)

          const workflowPromises = validUrls.map(async (urlItem, index) => {
            console.log(`开始处理第 ${index + 1}/${validUrls.length} 个URL:`, urlItem.url)
            
            try {
              const result = await executeWorkflow(urlItem, fileInputs)
              console.log(`URL ${urlItem.url} 处理成功:`, result)
              results.push({ url: urlItem.url, success: true, result })
              successCount++
              return {
                url: urlItem.url,
                type: urlItem.type,
                workflowRunId: result.workflow_run_id,
                taskId: result.task_id,
                status: result.data?.status || 'running',
                result: result
              }
            } catch (error) {
              console.error(`处理URL ${urlItem.url} 时出错:`, error)
              results.push({ url: urlItem.url, success: false, error: error.message })
              failureCount++
              return {
                url: urlItem.url,
                type: urlItem.type,
                status: 'failed',
                error: error.message
              }
            }
          })

          // 等待所有工作流执行完成
          scenarioData.workflows = await Promise.all(workflowPromises)
        }

        console.log('异步工作流处理完成:', {
          scenarioId: scenarioData.id,
          总数: form.urls.length,
          成功: successCount,
          失败: failureCount,
          详细结果: results
        })

        // 通知详情页面工作流处理完成
        // 这里可以通过事件总线、localStorage或其他方式通知详情页面
        const completionData = {
          scenarioId: scenarioData.id,
          status: successCount > 0 ? 'completed' : 'failed',
          successCount,
          failureCount,
          workflows: scenarioData.workflows,
          timestamp: new Date().toISOString()
        }

        // 使用localStorage通知详情页面
        localStorage.setItem(`workflow_completion_${scenarioData.id}`, JSON.stringify(completionData))
        
        // 触发自定义事件
        window.dispatchEvent(new CustomEvent('workflowCompleted', { 
          detail: completionData 
        }))

      } catch (error) {
        console.error('异步工作流处理失败:', error)
        
        // 通知详情页面处理失败
        const failureData = {
          scenarioId: scenarioData.id,
          status: 'failed',
          error: error.message,
          timestamp: new Date().toISOString()
        }
        
        localStorage.setItem(`workflow_completion_${scenarioData.id}`, JSON.stringify(failureData))
        window.dispatchEvent(new CustomEvent('workflowCompleted', { 
          detail: failureData 
        }))
      }
    }

    return {
      formRef,
      form,
      rules,
      fileList,
      uploadedFiles,
      supportedFormats,
      acceptedFileTypes,
      uploadAction,
      goBack,
      addUrl,
      removeUrl,
      createBusinessTable,
      handleUpload,
      handleUploadSuccess,
      handleUploadError,
      submitForm
    }
  }
}
</script>

<style scoped>
.create-business-scenario {
  padding: 24px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-header {
  background: white;
  padding: 20px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin-bottom: 24px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 4px;
  color: #606266;
  font-size: 14px;
}

.back-button:hover {
  color: #409eff;
}

.page-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.form-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.knowledge-form {
  padding: 32px;
}

.form-section {
  margin-bottom: 40px;
}

.form-section:last-child {
  margin-bottom: 0;
}

.section-title {
  margin: 0 0 24px 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  padding-bottom: 12px;
  border-bottom: 2px solid #e4e7ed;
}

.section-content {
  padding-left: 0;
}

.table-structure-container {
  display: flex;
  gap: 12px;
  align-items: center;
}

.table-structure-input {
  flex: 1;
}

.create-table-btn {
  flex-shrink: 0;
  white-space: nowrap;
}

.url-inputs-container {
  margin-bottom: 16px;
}

.url-input-row {
  display: flex;
  gap: 12px;
  align-items: center;
  margin-bottom: 12px;
}

.url-input-row:last-child {
  margin-bottom: 0;
}

.add-url-row {
  display: flex;
  justify-content: flex-start;
  margin-top: 8px;
}

.url-input {
  flex: 2;
}

.url-type-select {
  flex: 1;
  min-width: 120px;
}

.delete-btn {
  flex-shrink: 0;
  width: 60px;
}

.add-url-btn {
  width: 120px;
}

.remove-btn {
  color: #f56c6c;
  padding: 4px;
}

.remove-btn:hover {
  background-color: #fef0f0;
}

.url-type-select.is-error {
  border-color: #f56c6c;
}

.url-type-select.is-error :deep(.el-input__wrapper) {
  border-color: #f56c6c;
  box-shadow: 0 0 0 1px #f56c6c inset;
}

.url-type-select.is-error {
  border-color: #f56c6c;
}

.url-type-select.is-error :deep(.el-input__wrapper) {
  border-color: #f56c6c;
  box-shadow: 0 0 0 1px #f56c6c inset;
}
</style>